<?php
//获取根目录$path
require_once '../common/RootPath.php';
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

abstract class RequestHandler
{
    //判断参数是否为空
    public static function isEmptyArgs($args)
    {
       if (count($args)===0 && empty($args)){
           return 1;
       }else{
           return 0;
       }
    }

    public function __construct()
    {
        $this->getRequestData();
    }

    // 声明一个静态变量用于保存类的唯一实例
    public function getRequestData()
    {
        $method = $_SERVER['REQUEST_METHOD']; // 获取请求方法

        switch ($method) {
            case 'GET':
                $data = $_GET;
                $this->GetMapping($data);
                break;

            case 'POST':
                $data = $_POST;
                $this->PostMapping($data);
                break;

            case 'PUT':
                $json_data = file_get_contents("php://input");
                //$handleData = $this->removeUnderscore($json_data);
                $data = json_decode($json_data, true);
                $this->PutMapping($data);
                break;

            case 'DELETE':
                // PUT 和 DELETE 的数据通常通过 php://input 获取
                $json_data = file_get_contents("php://input");
                $data = json_decode($json_data, true);
                $this->DeleteMapping($data);
                break;

            default:

                echo 'message:Unsupported request json method ' . $method;

                break;
        }

    }

    //去除空格
    public function removeUnderscore($json_data)
    {
        // 解析 JSON 数据为关联数组
        $data = json_decode($json_data, true);
        $result = [];

        foreach ($data as $key => $value) {
            //去除两边空格
            $key = trim($key);

            // 如果值是数组或对象，则递归处理
            if (is_array($value)) {
                $value = removeUnderscore($value);
            }

            $result[$key] = trim($value);
        }

        return $result;
    }

    public abstract function GetMapping($args);

    public abstract function PostMapping($args);

    public abstract function PutMapping($args);

    public abstract function DeleteMapping($args);

}